﻿using Common.Logging;
using KeepAliveHttp.Http;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Threading.Tasks;
using System.Web;

namespace KeepAliveHttp
{
    /// <summary>
    /// LongPolling 的摘要说明
    /// </summary>
    public class LongPolling : IHttpAsyncHandler
    {
        public static readonly string SESSIONIDNAME = "sessionid";
        private static readonly ILog logger = LogManager.GetLogger(typeof(LongPolling));
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            var sessionId = context.Request.Params.Get(SESSIONIDNAME);
            var asyncResult = new AsyncResult(context, cb, extraData);
            if (string.IsNullOrEmpty(sessionId))
            {
                var error = "500 SessionId is null";
                context.Response.StatusCode = 500;
                logger.Error(error);
                asyncResult.Send(error);
                return asyncResult;
            }
            var connection = SessionManager.GetConnection(sessionId);
            if (connection == null)
            {
                var error = "404 SessionId:" + sessionId + " has no connection.";
                context.Response.StatusCode = 404;
                logger.Error(error);
                asyncResult.Send(error);
                return asyncResult;
            }
            //将新的异步请求实例关联对应的connection/session
            connection.AsyncResult = asyncResult;
            return asyncResult;
        }
        public void EndProcessRequest(IAsyncResult result)
        {
            (result as AsyncResult)?.Dispose();
        }
        public void ProcessRequest(HttpContext context)
        {
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}